<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{height: mainHeight+'px'}">
                <div class="panel-body">
                    <div class="btn-group" style="margin-bottom: 15px">
                        <el-button @click="create" type="primary" icon="fa fa-plus"
                                   size="small"> 新增
                        </el-button>
                        <el-button @click="list" type="primary" icon="fa fa-refresh"
                                   size="small"> 刷新
                        </el-button>
                        <el-button @click="toggleSelection(tableData,multipleSelection)" type="primary" icon="fa fa-toggle-on"
                                   size="small"> 反选
                        </el-button>
                        <el-button @click="deleteSelection(multipleSelection)" type="primary" icon="fa fa-trash"
                                   size="small"> 批量删除
                        </el-button>
                    </div>
                    <div class="bh-btn-group">
                        <div class="bh-search">
                            <el-input  size="medium" placeholder="请输入商品名称或关键字" v-model="search.name" class="input-with-select">
                                <el-button slot="append" icon="el-icon-search" @click="list"></el-button>
                            </el-input>
                        </div>
                    </div>
                    <el-table v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              @selection-change="handleSelectionChange"
                              ref="multipleTable"
                              :data="tableData"
                              tooltip-effect="dark"
                              :border="true" style="width: 100%">
                        <el-table-column type="selection" width="35px"></el-table-column>
                        <el-table-column prop="id" label="编号" width="60px"></el-table-column>
                        <el-table-column prop="thumb" label="封面图" width="120px">
                            <template slot-scope="scope">
                                <img :src="scope.row.thumb" style="height: 55px;"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="商品名称"></el-table-column>
                        <el-table-column prop="prices" label="市场价格" width="100px"></el-table-column>
                        <el-table-column prop="score" label="消耗积分" width="100px"></el-table-column>
                        <el-table-column prop="number" label="库存数量" width="100px"></el-table-column>
                        <el-table-column prop="changed" label="已兑换" width="80px"></el-table-column>
                        <el-table-column prop="status_text" label="状态" width="70px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.status_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sort_text" label="置顶" width="70px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.sort_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="270px">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>
                                    编辑</el-button>
                                <el-button icon="fa fa-trash"
                                           @click="destory(scope.row)" type="danger" size="mini" plain> 删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <div class="pagination-total">共 <em>{{pageData.total}}</em> 个商品</div>
                        <el-pagination  v-if="!loading && pageData && pageData.last_page > 1" background layout="prev, pager, next, jumper"
                                        :page-size="pageData.per_page"
                                        :total="pageData.total" :current-page="pageData.current_page"
                                        @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </div>
            </section>
        </el-main>
        <!-- 新增商品 -->
        <el-dialog
            :title="updateDialogTile"
            custom-class="bh-dialog"
            top="1vh"
            @open="resetForm('dialogForm')"
            :visible.sync="updateDialog"
            width="650px">
            <el-form :model="formData" size="medium" :status-icon="true" :rules="rules" ref="dialogForm" label-width="80px" class="demo-ruleForm">
                <el-form-item></el-form-item>
                <el-form-item required label="名称：" prop="name">
                    <el-input v-model="formData.name"  placeholder="请填写商品名称"></el-input>
                </el-form-item>
                <el-form-item required label="封面图：" prop="thumb">
                    <el-row :gutter="20">
                        <el-col :span="4" style="text-align: left">
                            <label class="btn btn-label" for="uploads">上传</label>
                            <input type="file" id="uploads" style="clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
                            <label class="btn btn-label" @click="rotateLeft">旋转</label>
                            <label class="btn btn-label" @click="finish('blob')">提交</label>
                        </el-col>
                        <el-col :span="18">
                            <div class="show-preview" :style="{'border': '1px dashed #ccc','width': '360px', 'height': '204px',  'overflow': 'hidden', 'margin': '5px', 'margin-left': '68px'}">
                                <div :style="previews.div" class="preview">
                                    <img :src="previews.url" :style="previews.img">
                                </div>
                            </div>
                        </el-col>
                        <el-col :span="24">
                            <div style="width: 100%;height: 255px;border: 1px dashed #ccc;margin-top: 5px">
                                <vueCropper
                                    ref="cropper"
                                    :img="formData.thumb"
                                    :outputSize="option.size"
                                    :outputType="option.outputType"
                                    :info="true"
                                    :full="option.full"
                                    :canMove="option.canMove"
                                    :autoCrop="option.autoCrop"
                                    :autoCropWidth="option.autoCropWidth"
                                    :autoCropHeight="option.autoCropHeight"
                                    :canMoveBox="option.canMoveBox"
                                    :fixedBox="option.fixedBox"
                                    :original="option.original"
                                    @realTime="realTime">
                                </vueCropper>
                            </div>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item required label="状态：" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio border :label="1">进行中</el-radio>
                        <el-radio border :label="2">已结束</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item required label="排序：" prop="sort">
                    <el-radio-group v-model="formData.sort">
                        <el-radio border :label="0">默认</el-radio>
                        <el-radio border :label="1">置顶</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="价格：" prop="prices">
                    <el-input v-model="formData.prices" type="number" placeholder="请填写市场价格"></el-input>
                </el-form-item>
                <el-form-item required label="积分：" prop="score">
                    <el-input v-model="formData.score" type="number" placeholder="请填写消耗积分"></el-input>
                </el-form-item>
                <el-form-item required label="库存：" prop="number">
                    <el-input v-model="formData.number" type="number" placeholder="请填写库存数量"></el-input>
                </el-form-item>
                <el-form-item label="介绍：" prop="intro">
                    <el-input type="textarea" v-model="formData.intro" placeholder="请填写商品介绍"></el-input>
                </el-form-item>
                <el-form-item label="详情：">
                    <el-upload
                        class="upload-demo"
                        :action="upload"
                        :headers="myHeaders"
                        multiple
                        :file-list="fileList"
                        list-type="picture" name="pic">
                        <el-button size="small" type="primary">点击上传详情</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item></el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="updateDialog = false">取 消</el-button>
            <el-button type="primary" @click="update('dialogForm')">确 定</el-button>
          </span>
        </el-dialog>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {MallList,MallUpdate,MallDestory,MallDestoryAll} from '../../utils/axios';
    import { VueCropper }  from 'vue-cropper';
    export default {
        components:{vBreadcrumb,VueCropper},
        data(){
            return {
                breadcumb:[{name: "商品管理"}],
                updateDialogTile:'',
                tableData:[],//列表数据
                pageData:[],//分页数据
                cates: [],
                updateDialog:false,
                search: {name: null},//筛选
                previews: {},
                option: {
                    size: 1,
                    full: false,
                    outputType: 'png',
                    canMove: true,
                    fixedBox: true,
                    autoCrop: true,
                    autoCropWidth: 360,
                    autoCropHeight: 204,
                    original: false,
                    canMoveBox: true
                },
                //用户表单
                formData:{id:'',name: '', thumb: '', prices: 0,score:0,number:0,intro:'',details:[],status:0,changed:0,sort:0},
                rules: {
                    name: [{ required: true, message: '请填写商品名称', trigger: 'blur' },],
                    thumb: [{ required: true, message: '请填写商品封面图链接地址', trigger: 'blur' },],
                    score: [{ required: true, message: '请填写商品消耗积分', trigger: 'blur' },],
                    number: [{ required: true, message: '请填写商品库存数量', trigger: 'blur' },],
                },
                multipleSelection: [],
                fileList: [],
            }
        },
        activated(){
            this.$store.dispatch('setActive', '/mall');
            this.list();
            this.previews =  {};
        },
        computed: {
            ...mapGetters(['active','mainHeight','loading','upload']),
            myHeaders(){
                var token = this.$storage.get('token');
                return {
                    Authorization:token.token_type+' ' + token.access_token,
                    Accept:'application/json'
                }
            },
        },
        methods:{
            //分页
            handleCurrentChange(val) {
                this.search.page = val;
                this.list();
            },
            //获取列表
            list(){
                this.$store.dispatch('setLoading', true);
                MallList({params: this.search}).then((response)=>{
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.tableData = response.data.data;
                        this.pageData = response.data;
                    }
                })
            },
            //编辑
            create(){
                this.formData = {id:'',name: '', thumb: '', prices: null,score:null,number:null,intro:'',details:[],status:1,changed:0,sort:0};
                this.updateDialog = true;
                this.updateDialogTile = '新增商品';
                this.fileList = [];
            },
            //编辑  prices: 0,score:0,number:0,intro:'',details:0,status:0,changed:0,sort:0
            edit(info){
                this.formData = {
                    id: info.id,
                    name: info.name,
                    thumb: info.thumb,
                    prices: info.prices,
                    score:info.score,
                    number:info.number,
                    status:info.status,
                    sort:info.sort,
                    changed:info.changed,
                    intro:info.intro,
                };
                this.fileList = info.details;
                this.updateDialogTile = '编辑商品信息';
                this.updateDialog = true;

            },
            //更新
            update(formName){
                if(this.formData.thumb.indexOf('blob:') != -1){
                    this.$message.error('请上传裁剪图片');
                    return false;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.formData.details = this.fileList;
                        MallUpdate(this.formData).then((response)=>{
                            if(response.code){
                                this.$message.error(response.msg);
                            }else{
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose:() =>{
                                        this.updateDialog = false;
                                        this.formData.details = [];
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //删除
            destory(info){
                this.$confirm('确定要删除该商品吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    MallDestory({params:{id: info.id}}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {});
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName]!==undefined) {
                    this.$refs[formName].resetFields();
                }
            },
            realTime (data) {
                this.previews = data
            },
            rotateLeft() {
                this.$refs.cropper.rotateLeft();
            },
            uploadImg (e) {
                var file = e.target.files[0];
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(e.target.value)) {
                    this.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种');
                    return false;
                }
                var reader = new FileReader();
                reader.onload = (e) => {
                    let data;
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result;
                    }
                    this.formData.thumb = data;
                };
                // 转化为blob
                reader.readAsArrayBuffer(file);
            },
            finish(){
                let formData = new FormData();
                this.$refs.cropper.getCropBlob((data) => {
                    let token = this.$storage.get('token');
                    formData.append("pic", data, this.formData.thumb);
                    this.$axios.post(this.upload, formData, {
                        headers:{
                            'Authorization':token.token_type+' ' + token.access_token,
                            'Accept':'application/json'
                        }
                    }).then((response)=>{
                        this.formData.thumb = response.data.data.path;
                    });
                })
            },
            //选择
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //反选
            toggleSelection(rows,selects){
                let rowsSet = new Set(rows);
                let selectsSet = new Set(selects);
                // 差集
                let differenceNew = Array.from(new Set(rows.concat(selects).filter(v => rowsSet.has(v) && !selectsSet.has(v))));
                this.$refs.multipleTable.clearSelection();
                differenceNew.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            },
            //批量删除
            deleteSelection(selects){
                var that = this;
                this.$confirm('此操作将永久删除选中行, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log(66);
                    MallDestoryAll({
                        params:{data:selects}
                    }).then((response) => {
                        console.log(33);
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        }
                    });
                }).catch(() => {});
            },
            // //多图上穿
            // handleRemove(file, fileList) {
            //     var _this = this;
            //     this.filePush = [];
            //     for(var i=0;fileList.length>i;i++){
            //         _this.filePush.push({name:fileList[i].name,url:fileList[i].url})
            //     }
            //     console.log(file);
            //     console.log(this.filePush);
            // },
            // handlePreview(file) {
            //     console.log(file);
            // },
            // handleSuccess(res,file) {
            //     var _this = this;
            //     if(res.code === 0){
            //         _this.filePush.push({name:file.name,url:res.data.path})
            //     }
            // },
        },
        filters: {
            channel: function (val,data) {
                if (!val) return '';
                let name = '';
                data.filter((item)=>{
                    if(item.id === val){
                        name = item.name;
                    }
                });
                return name;
            }
        }
    }
</script>
